﻿using Max.PH5_2006.ShoppingSite.DAL;
using Max.PH5_2006.ShoppingSite.IRespository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Max.PH5_2006.ShoppingSite.Respository
{
    public class BaseRespository<T> : IBaseRespository<T> where T : class, new()
    {
        PH52006ADbContext _context;

        //public BaseRespository() { }
        public BaseRespository(PH52006ADbContext context)
        {
            _context = context;
        }

        public int Add(T t)
        {
            _context.Set<T>().Add(t);
            int result = _context.SaveChanges();
            return result;
        }

        public async Task<int> AddAsync(T t)
        {
            _context.Set<T>().Add(t);
            int result = await _context.SaveChangesAsync();
            return result;
        }

        //删除的时候，用find找，find是根据T的主键类型来找的，所以不能直接用string（每个表的主键类型都有可能 不一样）
        public int Delete(List<dynamic> ids)
        {
            ids.ForEach(x => {
                var t = _context.Set<T>().Find(x);

                if(t != null) _context.Set<T>().Remove(t);

            });

            int result = _context.SaveChanges();
            return result;

        }

        public async Task<int> DeleteAsync(List<dynamic> ids)
        {
            ids.ForEach(x => {
                var t = _context.Set<T>().Find(x);

                if (t != null) _context.Set<T>().Remove(t);

            });

            int result = await _context.SaveChangesAsync();
            return result;
        }

        public IQueryable<T> Query()
        {
            var list = _context.Set<T>().AsQueryable();//.AsEnumerable();//

            return list;
        }

        public T QueryById(object id)
        {
            var t = _context.Set<T>().Find(id);
            return t;
        }

        public int Update(T t)
        {
            _context.Set<T>().Update(t);
            return _context.SaveChanges();
        }

        public async Task<int> UpdateAsync(T t)
        {
            _context.Set<T>().Update(t);
            return await _context.SaveChangesAsync();
        }
    }

}
